/*******************************************************************************
 * Copyright (c) 2014-8-17 @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a>.
 * All rights reserved.
 *
 * Contributors:
 *     <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> - initial API and implementation
 ******************************************************************************/
package com.foreveross.project.projectonline.web.controller;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.iff.infra.util.JsonHelper;
import org.iff.infra.util.MapHelper;

import com.foreveross.project.projectonline.config.Constants;
import com.foreveross.project.projectonline.model.TpMgtUser;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.render.JsonRender;

/**
 * @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> 
 * @since 2014-8-17
 */
@SuppressWarnings("unchecked")
public abstract class BaseController extends Controller {

	static String BASE_URI = null;

	public void createToken() {
		super.createToken(com.foreveross.project.projectonline.config.Constants.NAME_TOKEN);
	}

	public boolean validateToken() {
		if (getPara(com.foreveross.project.projectonline.config.Constants.NAME_TOKEN) == null) {
			return true;
		}
		return super.validateToken(com.foreveross.project.projectonline.config.Constants.NAME_TOKEN);
	}

	Map<String, Object> keepParaInJson(String paraName, String[] names) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (names == null || names.length < 1) {
			return jsonMap;
		}
		{
			try {
				String json = getPara("_JSON_");
				if (json != null && json.length() > 0) {
					Map<String, Object> temp = JsonHelper.toObject(HashMap.class, json);
					if (temp != null) {
						jsonMap = temp;
					}
				}
			} catch (Exception e) {
			}
		}
		for (String name : names) {
			String para = getPara(name);
			if (para != null) {
				jsonMap.put(name, para);
			}
		}
		for (Entry<String, Object> entry : jsonMap.entrySet()) {
			setAttr(entry.getKey(), entry.getValue());
		}
		if (!jsonMap.isEmpty()) {
			setAttr(paraName, JsonHelper.toJson(jsonMap));
		}
		return jsonMap;
	}

	String getIpAddr() {
		return getIpAddress(getRequest());
	}

	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("http_client_ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		// 如果是多级代理，那么取第一个ip为客户ip
		if (ip != null && ip.indexOf(",") != -1) {
			ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
		}
		return ip;
	}

	void addErrors(String key, String errorMgs) {
		Object obj = getAttr("errors");
		if (obj == null || !(obj instanceof Map)) {
			Map<String, Object> errors = new LinkedHashMap<String, Object>();
			errors.put(key, errorMgs);
			setAttr("errors", errors);
		} else {
			Map<String, Object> errors = (Map<String, Object>) obj;
			errors.put(key, errorMgs);
			setAttr("errors", errors);
		}
	}

	void addErrors(boolean whenTrue, String key, String errorMgs) {
		if (whenTrue) {
			addErrors(key, errorMgs);
		}
	}

	boolean hasErrors() {
		return getAttr("errors") != null;
	}

	void renderErrors() {
		Map result = MapHelper.toMap("result", MapHelper.toMap("errors", getAttr("errors")));
		if (isIE()) {
			render(new JsonRender(result).forIE());
		} else {
			renderJson(result);
		}
	}

	void renderSuccess() {
		Map result = MapHelper.toMap("result", MapHelper.toMap("success", "OK"));
		if (isIE()) {
			render(new JsonRender(result).forIE());
		} else {
			renderJson(result);
		}
	}

	String getBaseUri() {
		if (BASE_URI == null) {
			HttpServletRequest request = getRequest();
			StringBuilder sb = new StringBuilder();
			sb.append(request.getScheme()).append("://").append(request.getServerName());
			if (request.getServerPort() != 80) {
				sb.append(":").append(request.getServerPort());
			}
			sb.append(request.getContextPath()).toString();
			BASE_URI = sb.toString();
		}
		return BASE_URI;
	}

	TpMgtUser isLogin() {
		Object object = getSession(Constants.SESSION_USER_KEY);
		if (object == null || !(object instanceof TpMgtUser)) {
			return null;
		}
		setAttr("LOGIN_USER", object);
		return (TpMgtUser) object;
	}

	void setLogin(TpMgtUser user) {
		setSession(Constants.SESSION_USER_KEY, user);
		setAttr("LOGIN_USER", user);
	}

	void setSession(String key, Object value) {
		if (StrKit.isBlank(key)) {
			return;
		}
		if (value == null) {
			getRequest().getSession().removeAttribute(key);
		} else {
			getRequest().getSession().setAttribute(key, value);
		}
	}

	<T> T getSession(String key) {
		if (StrKit.isBlank(key)) {
			return null;
		}
		return (T) getRequest().getSession().getAttribute(key);
	}

	boolean isIE() {
		return getRequest().getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 ? true : false;
	}
}
